package cn.zk.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * MQ交换机与队列的创建，交换机与队列的绑定
 */
@Configuration
public class RabbitMQConfig {
    // 交换机名称
    public static final String EXCHANGE_TOPICS = "exchange_topics";
    // email队列名称
    public static final String QUEUE_EMAIL = "queue_email";
    // sms队列名称
    public static final String QUEUE_SMS = "queue_sms";

    public static final String ROUTING_KEY_EMAIL = "email.";


    /**
     * 交换机配置
     * ExchangeBuilder提供了fanout、direct、topic、header交换机类型的配置
     * @return the exchange
     */
    // TOPIC交换机
    @Bean(EXCHANGE_TOPICS)// 容器中的别名
    public Exchange exchangeTopicsInform() {
        //durable(true)持久化，消息队列重启后交换机仍然存在
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS)// mq中交换机的别名
                .durable(true)
                .build();
    }

    //声明队列
    @Bean(QUEUE_SMS)
    public Queue queueInformSms() {
        Queue queue = new Queue(QUEUE_SMS,true);
        return queue;
    }

    //声明队列
    @Bean(QUEUE_EMAIL)
    public Queue queueInformEmail() {
        Queue queue = new Queue(QUEUE_EMAIL,true);
        return queue;
    }

    /**
     * 通配符：
     *      Routingkey 一般都是有一个或多个单词组成，多个单词之间以”.”分割
     *      #：匹配一个或多个词
     *      *：匹配不多不少恰好1个词
     * channel.queueBind(INFORM_QUEUE_SMS,"inform_exchange_topic","inform.#.sms.#");
     * 绑定队列到交换机 .
     *
     * @param queue    the queue
     * @param exchange the exchange
     * @return the binding
     */
    // 队列绑定交换机
    @Bean
    public Binding bindingQueueInformSms(@Qualifier(QUEUE_SMS) Queue queue,
                                            @Qualifier(EXCHANGE_TOPICS) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("sms.#").noargs();
    }

    @Bean
    public Binding bindingQueueInformEmail(@Qualifier(QUEUE_EMAIL) Queue queue,
                                            @Qualifier(EXCHANGE_TOPICS) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY_EMAIL+"#").noargs();
    }



}
